package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.atguigu.common.uuid.IdUtils;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Author panghl
 * @Date 2020/12/31 21:50
 * @Description TODO
 **/
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //工具类获取值
         String endpoint = ConstantPropertiesUtils.END_POIND;
         String accessKeyId = ConstantPropertiesUtils.KEY_ID;
         String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
         String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String filename = file.getOriginalFilename();

            //1.在文件名称里面添加随机唯一的值
            //filename = IdUtils.fastSimpleUUID() + filename;
            //2.把文件按照日期进行分类
            // 2019/11/12/01.jpg  获取当前日期
            //String datePath = new DateTime().toString("yyyy/MM/dd");
            filename = new DateTime().toString("yyyy/MM/dd") + "/" + IdUtils.fastSimpleUUID() + filename;

            //调用oss方法实现上传
            //第一个参数 Bucket名称
            //第二个参数 上传到oss文件路径和文件名称 /aa/bb/1.jpg
            //第三个参数 上传文件输入流
            // https://edu-425.oss-cn-chengdu.aliyuncs.com/testdlrb.jpg
            ossClient.putObject(bucketName, filename, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //把上传之后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            return "https://" + bucketName + "." + endpoint + "/" + filename;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


}
